package day12.network;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {
    public void start(){
        //新启动一个线程
        new Thread(){
            @Override
            public void run() {
                try{
                    ServerSocket ss = new ServerSocket(8000);
                    System.out.println("服务已启动");
                    while(true){
                        Socket s = ss.accept();
                        // socket连接通道，交给线程, 来并行执行通信过程
                        CommunicationThread t = new CommunicationThread(s);
                        t.start();
                    }
                }catch (Exception e){
                    System.out.println("端口被占用,服务异常停止");
                }
            }
        }.start();
    }
    public class CommunicationThread extends Thread {
        Socket s;
        public CommunicationThread(Socket s) {
            this.s = s;
        }

        @Override
        public void run() {
            try {
                /*
                通信协议
                流程
                1. 接收
                2. 发送

                数据格式
                1. GBK编码字符
                2. 一行文本，末尾有换行符
                BR -- BSR -- 网络输入流
                PrintWriter -- OSW -- 网络输出流
                 */
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream(),"GBK"));
                // Printer 有println方法
                PrintWriter out = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), "GBK"));
                String line;
                while((line = in.readLine()) != null){
                    out.println(line);
                    out.flush();
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("客户端已断开");
        }
    }

    public static void main(String[] args) {
        EchoServer server = new EchoServer();
        server.start();
    }
}
